package com.jingdianjichi.oss.service.impl;

import com.jingdianjichi.oss.entity.FileInfo;
import com.jingdianjichi.oss.service.StorageService;
import com.jingdianjichi.oss.utils.MinioUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

/**
 * minio实现,MinioUtil层是和minio的原子性的操作,这个service层,你可以做任何你想做的,逻辑了都是可以的,我们这里没啥特殊的逻辑的
 */
@Service
public class MinioStorageServiceImpl implements StorageService {

    //minio工具类
    @Resource
    private MinioUtil minioUtil;

    //创建桶
    @Override
    @SneakyThrows       //这个注解就是lombock的注解,这样我们就不用自己去throw了.他会在编译的时期自动帮我们把这个异常跑出去的
    public void createBucket(String bucket) {
        minioUtil.createBucket(bucket);
    }


    //上传文件
    @Override
    @SneakyThrows
    public void uploadFile(MultipartFile uploadFile, String bucket, String objectName) {
        String name = uploadFile.getName();

        String[] split = name.split(".");
        String MIME = split[1];


        //有点小逻辑,就是看看有没有这个桶
        minioUtil.createBucket(bucket);

        if (objectName!=null)
        {
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,objectName+"/"+uploadFile.getName(),MIME);
        }else
        {
            //objectName不是必填的亲
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,uploadFile.getName(),MIME);
        }
    }

    //获得所有的桶
    @Override
    @SneakyThrows
    public List<String> getAllBucket() {
        return minioUtil.getAllBucket();
    }

    //获得桶中的所有文件对象
    @Override
    @SneakyThrows
    public List<FileInfo> getAllFile(String bucket) {
        return minioUtil.getAllFile(bucket);
    }

    //下载文件
    @Override
    @SneakyThrows
    public InputStream downLoad(String bucket, String objectName) {
        InputStream inputStream = minioUtil.downLoad(bucket, objectName);
        return inputStream;
    }

    //删除桶
    @Override
    @SneakyThrows
    public void deleteBucket(String bucket) {
        minioUtil.deleteBucket(bucket);
    }

    //删除文件
    @Override
    @SneakyThrows
    public void deleteObject(String bucket, String objectName) {
        minioUtil.deleteObject(bucket,objectName);
    }
}
